const request = require('../../../api/request');

Page({
  data: {
    bindType: 'select', // select/create
    searchKeyword: '',
    memberList: [],
    genderOptions: ['男', '女'],
    genderIndex: 0,
    clanList: [],
    clanIndex: 0,
    branchList: [],
    branchIndex: 0,
    loadingClans: false,
    loadingBranches: false
  },

  onLoad() {
    this.loadMembers();
    this.loadClans();
  },

  // 切换绑定方式
  onTypeChange(e) {
    this.setData({ bindType: e.detail.value });
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.loadMembers(keyword);
  },

  // 加载成员列表
  loadMembers(keyword = '') {
    request.get('/members/search', { q: keyword, limit: 20 }).then(res => {
      this.setData({ memberList: res });
    });
  },

  // 加载家族列表
  loadClans() {
    this.setData({ loadingClans: true });
    request.get('/api/v1/clans').then(res => {
      if (res && res.records && res.records.length > 0) {
        const clanList = res.records;
        this.setData({ 
          clanList,
          clanIndex: 0
        });
        this.loadBranches(clanList[0].id);
      }
    }).finally(() => {
      this.setData({ loadingClans: false });
    });
  },

  // 加载分支列表
  loadBranches(clanId) {
    this.setData({ loadingBranches: true, branchList: [] });
    request.get('/api/v1/branch', { clanId }).then(res => {
      if (res && res.records && res.records.length > 0) {
        this.setData({
          branchList: res.records,
          branchIndex: 0
        });
      }
    }).finally(() => {
      this.setData({ loadingBranches: false });
    });
  },

  // 家族选择变更
  onClanChange(e) {
    const index = parseInt(e.detail.value);
    this.setData({ clanIndex: index });
    if (this.data.clanList[index]) {
      this.loadBranches(this.data.clanList[index].id);
    }
  },

  // 分支选择变更
  onBranchChange(e) {
    this.setData({ branchIndex: parseInt(e.detail.value) });
  },

  // 选择已有成员并绑定
  onSelectMember(e) {
    const memberId = e.currentTarget.dataset.id;
    wx.showLoading({ title: '绑定中...' });
    request.post('/api/v1/users/bind-member', { memberId }).then(() => {
      wx.hideLoading();
      wx.showToast({ title: '绑定成功', icon: 'success' });
      this.refreshUserInfo();
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: err.msg || '绑定失败', icon: 'none' });
    });
  },

  // 性别选择
  onGenderChange(e) {
    this.setData({ genderIndex: e.detail.value });
  },

  // 新建成员并绑定
  onCreateMember(e) {
    const form = e.detail.value;
    if (!form.name) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    
    const gender = this.data.genderOptions[this.data.genderIndex] === '男' ? 'M' : 'F';
    
    // 获取家族和分支信息
    const clan = this.data.clanList[this.data.clanIndex] || {};
    const branch = this.data.branchList[this.data.branchIndex] || {};

    wx.showLoading({ title: '提交申请中...' });
    
    // 提交成员审核申请
    request.post('/api/v1/members/submit-for-approval', {
      name: form.name,
      gender,
      clanId: clan.id,
      branchId: branch.id,
      birthDate: form.birthDate || null,
      story: form.story || '',
      contact: form.contact || ''
    }).then(() => {
      wx.hideLoading();
      wx.showModal({
        title: '提交成功',
        content: '您的成员申请已提交，管理员审核通过后将自动绑定，请耐心等待。',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: err.msg || '提交失败', icon: 'none' });
    });
  },

  // 绑定后刷新用户信息
  refreshUserInfo() {
    request.get('/api/v1/users/me').then(user => {
      const userInfo = wx.getStorageSync('userInfo') || {};
      userInfo.memberId = user.memberId;
      wx.setStorageSync('userInfo', userInfo);
      wx.switchTab({ url: '/pages/index/index' });
    });
  }
}); 